package com.bdqn.t308.aop;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

/**
 * 打印日志
 */
public class UserServiceLogger {

    private static final Logger logger = Logger.getLogger(UserServiceLogger.class);

    /**
     * 前置增强
     * @param joinPoint
     */
    public void before(JoinPoint joinPoint){
        logger.info("调用"+joinPoint.getTarget()+"的"+joinPoint.getSignature().getName());
    }


    /**
     * 环绕增强
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
        logger.info("调用"+joinPoint.getTarget()+"的"+joinPoint.getSignature().getName());
        try {
            Object result = joinPoint.proceed();        //执行目标方法并获得返回值
            return result;
        } catch (Throwable e){
            logger.error("执行方法发生异常"+e);
            throw e;
        } finally {
            logger.info("执行方法结束！");
        }

    }


    /**
     * 返回增强
     * @param joinPoint
     * @param obj
     */
    public void afterRuning(JoinPoint joinPoint, Object obj){
        logger.info("调用"+joinPoint.getTarget()+"的"+joinPoint.getSignature().getName()+"，返回："+obj);
    }

    /**
     * 异常抛出增强
     * @param joinPoint
     * @param ex
     */
    public void throwError(JoinPoint joinPoint,RuntimeException ex){
        logger.info("调用"+joinPoint.getTarget()+"的"+joinPoint.getSignature().getName()
                +"方法，发生异常："+ex);
    }

    /**
     * 最终增强
     */
    public void after(JoinPoint joinPoint){
        logger.info("调用"+joinPoint.getTarget()+"的"+joinPoint.getSignature().getName()
                +"方法结束了！！");
    }
}
